﻿using DW.Library;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Path = System.IO.Path;

namespace Update
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public string[] args;

        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Update();
        }

        private async void Update()
        {
            // 获取 version.json 内容
            string content = OSSHelper.GetObjectContent($"{Config.AutoUpdateDirectory}/version.json");
            var versionInfo = JsonSerializer.Deserialize<VersionInfo>(content);

            if (versionInfo != null && !string.IsNullOrEmpty(versionInfo.description))
            {
                rb_Content.Document.Blocks.Clear();
                rb_Content.Document.Blocks.Add(new Paragraph(new Run(versionInfo.description)));
            }
            else
            {
                rb_Content.Document.Blocks.Clear();
                rb_Content.Document.Blocks.Add(new Paragraph(new Run("暂无更新说明。")));
            }
            args = App.Args;
            if (args.Length < 2)
            {
                MessageBox.Show("参数不足。");
                return;
            }

            string processName = args[0];
            string exeName = args[1];
            string appDir = AppDomain.CurrentDomain.BaseDirectory;

            //string appDir = @"E:\DW_Git\TouchTBData\TouchTBData\bin\Debug\";
            //string processName = "TouchTBData";
            //string exeName = "TouchTBData.exe";

            string zipFile = Path.Combine(Path.GetTempPath(), $"{DateTime.Now.ToString("MMddHHmmss")}" + versionInfo.file);
            // 下载 zip 文件到临时目录
            try
            {
                await OSSHelper.GetObject($"{Config.AutoUpdateDirectory}/{versionInfo.file}", zipFile);
            }
            catch (Exception ex)
            {
                MessageBox.Show("下载失败: " + ex.Message);
                return;
            }

            // 1. 等待主程序完全退出
            if (!string.IsNullOrEmpty(processName))
            {
                foreach (var p in Process.GetProcessesByName(processName))
                {
                    try
                    {
                        if (!p.HasExited)
                        {
                            p.WaitForExit(10000); // 最多等10秒
                        }
                    }
                    catch { }
                }
            }

            // 2. 解压 zipFile 到 appDir（覆盖）
            try
            {
                await Task.Delay(5000);
                ZipFile.ExtractToDirectory(zipFile, appDir, true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("解压失败: " + ex.Message);
            }

            // 3. 启动主程序
            if (!string.IsNullOrEmpty(exeName))
            {
                ProcessStartInfo processStartInfo = new ProcessStartInfo();
                processStartInfo.UseShellExecute = true;
                processStartInfo.WorkingDirectory = appDir;
                processStartInfo.FileName = Path.Combine(appDir, exeName);
                Process.Start(processStartInfo);

            }
        }
    }
}